const _BookListKey = 'chrome-novel-plugin_bookList'
const _bookList = []
let bookList = new Proxy(_bookList, {
  get(target, prop, receiver) {
    return Reflect.get(target, prop, receiver)
  },
  set(target, prop, value, receiver) {
    let result = Reflect.set(target, prop, value, receiver)
    if (prop == 'length') {
      renderBookList()
      console.log('target', target)
      chrome.runtime.sendMessage({
        action: 'setBookList',
        preload: target,
      })
    }
    return result
  },
})

let activeType = 0
// match url 是不变的，故获取一次后可缓存下来
let urlList = []
let cacheInfo = {}
document.addEventListener('DOMContentLoaded', async () => {
  const storageResult = await chrome.storage.local.get(_BookListKey)
  bookList.push(...(storageResult[_BookListKey] || []))

  await getMatchUrls()

  await renderPage()
})

inputRef.addEventListener('keypress', handleKeyPress)
addBtnRef.addEventListener('click', handleAdd)
listWrapRef.addEventListener('click', handleDelete)
iconChangeRef.addEventListener('click', () => {
  activeType = activeType ^ 1
  renderPage()
})
refreshBtnRef.addEventListener('click', renderPage)

async function renderPage() {
  if (activeType == 0) {
    initInput()
    renderBookList()
  } else {
    await renderUrlList()
  }
}

/**获取所有可以匹配的url */
async function getMatchUrls() {
  if (urlList.length) return
  let manifest = await chrome.runtime.getManifest()
  let { content_scripts } = manifest
  urlList = content_scripts.reduce((arr, { matches }) => (arr.push(...matches), arr), []).map((url) => url.replace(/\*:\/\/(.*)\/\*/, '$1'))
}

function renderUrlList() {
  let fragment = document.createDocumentFragment()
  urlList.forEach((url) => {
    let li = document.createElement('li')
    let a = document.createElement('a')
    a.href = 'https://' + url
    a.target = '_blank'
    a.innerText = url
    a.style.marginTop = '4px'
    li.append(a)
    fragment.appendChild(li)
  })
  listWrapRef.innerHTML = ''
  listWrapRef.appendChild(fragment)
}

async function initInput() {
  const tabs = await chrome.tabs.query({
    active: true,
    currentWindow: true,
  })
  if (!tabs) return
  chrome.tabs.sendMessage(tabs[0].id, { action: 'getBookNameFromContent' }, ({ bookName, bookLink } = {}) => {
    window.bookName = bookName
    bookName && (cacheInfo[bookName] = bookLink)
    inputRef.value = bookList.some((item) => item.bookName == bookName) ? '' : bookName || ''
  })
}

function renderBookList() {
  let fragment = document.createDocumentFragment()
  bookList.forEach(({ bookName, bookLink, chapterTitle, chapterLink }, index) => {
    let div = document.createElement('div')
    div.className = 'row-wrap'

    let titleWrap = document.createElement('div')
    titleWrap.className = 'title-wrap'
    div.append(titleWrap)

    if (bookLink || chapterLink) {
      let a = createAnchorElement(bookLink ? bookLink : chapterLink.replace(/[\w-]*\.html$/, ''), bookName)
      a.className = 'title'
      titleWrap.append(a)
    } else {
      let span = document.createElement('span')
      span.className = 'title'
      span.innerText = bookName
      titleWrap.append(span)
    }
  
    let updateNumDom = document.createElement('span')
    titleWrap.append(updateNumDom)


    let img = document.createElement('img')
    img.src = '../img/close.svg'
    img.dataset.index = index
    div.append(img)

    let li = document.createElement('li')
    li.append(div)

    if (chapterTitle) {
      let a = createAnchorElement(chapterLink, `读至：${chapterTitle}`)
      a.style.marginTop = '4px'
      li.append(a)
    }

    if (bookLink) {
      getUpdateChapter(bookLink).then(({ link, text }) => {
        if (!text) return
        console.log(bookName, chapterTitle, link, text)
        let a = createAnchorElement(link, `更新：${text}`)
        a.style.marginTop = '4px'

        let cur =  extractChapterNumber(chapterTitle)
        let lastest = extractChapterNumber(text)
        console.log('章节数:', cur, lastest)
        if (cur && lastest && lastest - cur > 0) {
          updateNumDom.innerText = lastest - cur
          updateNumDom.className = 'badge'
        }

        li.append(a)
      })
    }

    fragment.appendChild(li)
  })
  listWrapRef.innerHTML = ''
  listWrapRef.appendChild(fragment)
}

function createAnchorElement(href, text) {
  let a = document.createElement('a')
  a.target = '_blank'
  a.href = href
  a.innerText = text
  return a
}

function handleDelete(e) {
  if (e.target.tagName != 'IMG') return
  let { index } = e.target.dataset
  let [{ bookName }] = bookList.splice(index, 1)
  if (bookName == window.bookName) {
    inputRef.value = window.bookName
  }
}

function handleAdd() {
  if (!inputRef.value) return
  bookList.push({
    bookName: inputRef.value,
    bookLink: cacheInfo[inputRef.value] || '',
    chapterLink: '',
    chapterTitle: '',
  })
  inputRef.value = ''
}

function handleKeyPress(e) {
  if (e.keyCode == 13) {
    handleAdd()
    e.preventDefault()
  }
}

/**获取最新章节及链接 */
async function getUpdateChapter(bookLink) {
  const { host } = new URL(bookLink)

  let html = await fetchChapterHtml(bookLink)
  let dom = {}

  if (/\.\d[d|s]xs\.cc$/.test(host)) {
    host = "*.7dxs.cc"
  }

  switch (host) {
    case 'www.3qdu.com':
    case 'www.3qdu.net':
    case 'www.x3qdu.com':
    case 'www.3qxsw.com': {
      dom = html.querySelector('.catalogyb li a')
      break
    }
    case 'm.3qdu.com':
    case 'm.3qxsw.com':
    case 'sk.3qxsw.com':
    case 'shouji.xstuijian.com':
    case '*.7dxs.cc': {
      dom = html.querySelector('.tab .p3 a')
      break
    }
    case 'www.92yanqing.com':
    case 'www.92yanqing.net': {
      dom = html.querySelector('.bookdes p a[rel="chapter"]')
      break
    }
    case 'www.gdbzkz.info':
    case 'www.gdbzkz.net':
    case 'www.blqukk.cc':
    case 'www.123vvxw.cc':
    case 'www.yqxsg.cc': {
      dom = html.querySelector('.info .last a')
      break
    }
    case 'www.23xsww.cc': 
    case 'www.biqusa.com': 
    case 'www.aixiashu.info': {
      dom = html.querySelector('#info p:last-of-type a')
      break
    }
    case 'www.lwcs.co': {
      dom = html.querySelector('.info p:last-of-type a')
      break
    }
    case 'www.paozww.com':
    case 'www.paozw.org':
    case 'www.douyinxs.com':
    case 'www.ddyveshu.cc': {
      dom = html.querySelector('#list dd a')
      break
    }
    case 'www.xs55.org': {
      dom = html.querySelector('#info p a[rel="chapter"]')
      break
    }
    case 'www.yuyouku.com': {
      dom = html.querySelector('.panel.panel-default .list-group .list-group-item a')
      break
    }
    case 'www.6sgl.com': {
      dom = html.querySelector('#info p:nth-of-type(5) a')
      break
    }
    default: {
      console.warn(`🎃 ${host}还没有配置获取最新章节的方法，请配置！`)
      return {}
    }
  }

  let linkURL = new URL(dom.href.replace(location.origin, ''), bookLink)
  const link = linkURL.href
  console.log(linkURL, link, dom.innerText)
  return {
    link,
    text: dom.innerText,
  }
}

/**获取文章 */
async function fetchChapterHtml(bookLink) {
  const { host } = new URL(bookLink)
  let isUseGbk = [
    'www.3qdu.com',
    'www.3qdu.net',
    'www.x3qdu.com',
    'www.blqukk.cc',
    'www.123vvxw.cc',
    'www.yqxsg.cc',
    'www.23xsww.cc',
    'www.ddyveshu.cc',
    'www.yuyouku.com',
  ].includes(host)
  const response = await fetch(bookLink)
  const decoder = new TextDecoder(isUseGbk ? 'gbk' : 'utf8')
  const html = decoder.decode(await response.arrayBuffer())
  let domParse = new DOMParser()
  return domParse.parseFromString(html, 'text/html')
}

/**提取章节数 */
function extractChapterNumber(text) {
  let match = text.match(/[第]?([零一二三四五六七八九十百千万亿\d]+)[章|节|回|卷|\.|\s]?/)

  if (match && match[1]) {
    const chapterNumber = match[1]
    // 如果是中文数字，转换为阿拉伯数字
    if (/[零一二三四五六七八九十百千万亿]/.test(chapterNumber)) {
      return chineseToNumber(chapterNumber)
    } else {
      return parseInt(chapterNumber, 10)
    }
  }
  return null
}

// 中文数字转阿拉伯数字的辅助函数
function chineseToNumber(chinese) {
  const chineseNumbers = {
    零: 0,
    一: 1,
    二: 2,
    三: 3,
    四: 4,
    五: 5,
    六: 6,
    七: 7,
    八: 8,
    九: 9,
    十: { value: 10, next: 1 },
    百: { value: 100, next: 10 },
    千: { value: 1000, next: 100 },
    万: { value: 10000, next: 1000 },
    亿: { value: 100000000, next: 10000 },
  }

  let total = 0
  let current = 0
  let currentBase = 1 // 当前未明确单位时的基准值（默认为个位）

  for (let i = 0; i < chinese.length; i++) {
    const char = chinese[i]
    const num = chineseNumbers[char]
    if (num === undefined) return null

    if (char === '零') {
      currentBase = 1 // 遇到“零”后，后续数字视为个位
      continue
    }

    if (typeof num === 'object') {
      // 处理单位（十、百、千、万、亿）
      if (num.value === 10 && current === 0) {
        current = 1 // 处理“十五”这种没有前缀的情况
      }
      current = current || 1 // 如“百”默认为1百
      total += current * num.value
      current = 0
      currentBase = num.next // 更新后续数字的基准单位
    } else {
      current += num // 普通数字累加
    }
  }

  // 处理末尾剩余的数字（如“一千五”中的“五”）
  total += current * currentBase
  return total
}
